package JavaEE.ManyThread9;
import java.util.*;
import java.util.concurrent.CountDownLatch;

// CountDownLatch -> "闭锁"/"锁存器" (并不都合理,不过多纠结)
// 可以用于多线程中类似:"8个运动员赛跑,判断何时比赛结束"
public class Demo2 {
    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(8);
        for(int i = 0;i < 8;i++){
            int id = i;
            Thread t1 = new Thread(() -> {
                try{
                    System.out.println("赛道 " + id + " 运行结束");
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                // 只有countDown运行了8次,才代表"比赛结束"
                countDownLatch.countDown();
            });
            t1.start();
        }
        try {
            countDownLatch.await(); // 主线程等待所有赛道完成
            System.out.println("所有赛道比赛结束！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
